<?php
/**
 * ===============================================
 * 版权所有 2019-2050 青岛铁锤科技有限公司，并保留所有权利。
 * 网站地址: http://www.huaxianling.com
 * ===============================================
 * Author: Happy dong
 * Created Time: 2019-10-19 10:40
 *
 * Version: 2.0
 */

namespace App\Modules\Pay\Services;

use App\Exceptions\AllValidatorException;
use App\Exceptions\DbException;
use App\Exceptions\NotFoundException;
use App\Modules\Cashier\Repositories\BillRepository;
use App\Modules\Coupon\Repositories\CouponListRepository;
use App\Modules\Employee\Repositories\EmployeeRepository;
use App\Modules\Employee\Repositories\EmployeeRoyaltyRepository;
use App\Modules\Employee\Repositories\UserCoinRepository;
use App\Modules\Inventory\Repositories\GoodsOrderItemsRepository;
use App\Modules\Inventory\Repositories\GoodsOrderRepository;
use App\Modules\Inventory\Repositories\GoodsRepository;
use App\Modules\Inventory\Repositories\GoodsStockRepository;
use App\Modules\Inventory\Repositories\SalePurchaseRepository;
use App\Modules\Member\Repositoryies\MemberCoinRepository;
use App\Modules\Member\Repositoryies\MemberRepository;
use App\Modules\MemberCard\Repositores\CardTypeRepository;
use App\Modules\MemberCard\Repositores\MemberCardFlowRepository;
use App\Modules\MemberCard\Repositores\MemberCardOrderRepository;
use App\Modules\MemberCard\Repositores\MemberCardRepository;
use App\Modules\Message\Repositories\MessageRepository;
use App\Modules\Order\Repositories\OrderItemRepository;
use App\Modules\Order\Repositories\OrderRepository;
use App\Modules\Order\Repositories\RoyaltyRepository;
use App\Modules\Order\Services\HaircutPriceService;
use App\Modules\Service\Repositories\ServiceRepository;
use App\Modules\Store\Repositories\StorePaymentRoyaltyRepository;
use App\Modules\Store\Repositories\StoreRepository;
use App\Modules\System\Repositories\AmountFlowRepository;
use Flower\Core\Repository\Eloquent\BaseService;
use Illuminate\Support\Facades\DB;

class PayService extends BaseService
{
	use HaircutPriceService;

	private $orderRepository;
	private $memberRepository;
	private $cardRepository;
	private $memberCoinRepository;
	private $orderItemRepository;
	private $userCoinRepository;
	private $storeRepository;
	private $amountFlowRepository;
	private $messageRepository;
	private $royaltyRepository;
	private $memberCardFlowRepository;
	private $employeeRoyaltyRepository;
	private $storePaymentRoyaltyRepository;
	private $cardTypeRepository;
	private $employeeRepository;
	private $billRepository;
	private $salePurchaseRepository;
	private $goodsStockRepository;
	private $goodsRepository;
	private $goodsOrderRepository;
	private $memberCardOrderRepository;
	private $goodsOrderItemsRepository;
	private $couponListRepository;
	public function __construct(OrderRepository $orderRepository, MemberRepository $memberRepository, ServiceRepository $serviceRepository, MemberCardRepository $cardRepository, MemberCoinRepository $memberCoinRepository, UserCoinRepository $userCoinRepository, OrderItemRepository $orderItemRepository, StoreRepository $storeRepository, MemberCardFlowRepository $memberCardFlowRepository, EmployeeRoyaltyRepository $employeeRoyaltyRepository, StorePaymentRoyaltyRepository $storePaymentRoyaltyRepository, AmountFlowRepository $amountFlowRepository, MessageRepository $messageRepository, RoyaltyRepository $royaltyRepository, CardTypeRepository $cardTypeRepository, EmployeeRepository $employeeRepository, BillRepository $billRepository, SalePurchaseRepository $salePurchaseRepository, GoodsStockRepository $goodsStockRepository, GoodsRepository $goodsRepository, GoodsOrderRepository $goodsOrderRepository, MemberCardOrderRepository $memberCardOrderRepository,GoodsOrderItemsRepository $goodsOrderItemsRepository,CouponListRepository $couponListRepository)
	{
		$this->orderRepository = $orderRepository;
		$this->memberRepository = $memberRepository;
		$this->serviceRepository = $serviceRepository;
		$this->cardRepository = $cardRepository;
		$this->memberCoinRepository = $memberCoinRepository;
		$this->userCoinRepository = $userCoinRepository;
		$this->orderItemRepository = $orderItemRepository;
		$this->storeRepository = $storeRepository;
		$this->memberCardFlowRepository = $memberCardFlowRepository;
		$this->memberCardOrderRepository = $memberCardOrderRepository;
		$this->employeeRoyaltyRepository = $employeeRoyaltyRepository;
		$this->storePaymentRoyaltyRepository = $storePaymentRoyaltyRepository;
		$this->amountFlowRepository = $amountFlowRepository;
		$this->messageRepository = $messageRepository;
		$this->royaltyRepository = $royaltyRepository;
		$this->cardTypeRepository = $cardTypeRepository;
		$this->employeeRepository = $employeeRepository;
		$this->billRepository = $billRepository;
		$this->salePurchaseRepository = $salePurchaseRepository;
		$this->goodsStockRepository = $goodsStockRepository;
		$this->goodsOrderRepository = $goodsOrderRepository;
		$this->goodsRepository = $goodsRepository;
		$this->goodsOrderItemsRepository = $goodsOrderItemsRepository;
		$this->couponListRepository = $couponListRepository;

	}

//	public function importExcel(){
//	}
	/**
	 * 系统支付
	 * @param $order
	 * @param $type
	 * @param $billId
	 * @param $params
	 * @throws AllValidatorException
	 * @throws DbException
	 * @throws NotFoundException
	 */
	public function Pay($order, $type, $billId, $params)
	{
		switch ($type) {
			case 1:
				$this->servicePay($order, $billId, $params);
				break;
			case 2:
				$this->memberCardPay($order, $billId, $params);
				break;
			case 3:
				$this->goodsPay($order, $billId, $params);
				break;
			case 4:
				$this->memberCardRecharge($order, $billId, $params);
				break;

		}
	}

	/**
	 * 服务订单支付
	 * @param $order
	 * @param $billId
	 * @param $params
	 * @return mixed
	 * @throws AllValidatorException
	 * @throws NotFoundException
	 */
	protected function servicePay($order, $billId, $params)
	{
		list($orderItems, $payment, $memberCard, $changeReason, $finishRemark,$couponCode) = array_values($params);
		// 读取订单关联的服务id
		if (empty($order->items)) {
			throw new NotFoundException(['msg' => '该订单服务异常，请检测后提交！']);
		}

		$coupon = null;
		if(!empty($couponCode)){
			// 验证优惠券是否存在
			$coupon = $this->couponListRepository->isExisted($couponCode);
		}

		DB::beginTransaction();

		// 计算价格
		$originPrice = $realPrice = $totalCount = 0;
		foreach ($orderItems as $v){
		    if(empty($v['service'])) continue;
			$originPrice += $v['service']->price * $v['count'];
			$realPrice += $v['price'] * $v['count'];
			$totalCount += $v['count'];
		}

		$serviceIds = array_column($orderItems, 'service_id');
		// 计算会员卡Id
		$memberCardId = empty($memberCard) ? 0 : $memberCard->id;
		// 查询服务价格
		$priceInfo = $this->hairCutTotalPrice($orderItems, $payment, $order->member_card_id, false);
		// 验证会员卡余额
		$memberCardHandle = $this->memberCardConsumeHandle($memberCardId, $serviceIds, $realPrice, $payment);
		// 更新订单内容
		$order = $this->orderRepository->finishedById($order->id, $realPrice, $originPrice, $payment, $memberCardId, $finishRemark, $changeReason);
		// 处理订单详情 积分奖励 和 提成
		$isOnline = empty($order->appointment_id) ? false : true;
		$result = $this->orderItemMemberCoinHandle($billId, $order, $orderItems, $payment, $priceInfo, $isOnline,$coupon);
		$flag = $this->memberCardFlowMessage($result['order'], $memberCardHandle, $totalCount);
		// 计算等级的订单数
		$this->storeLevelHandel($result['order']);

		$result['flag'] && $flag ? DB::commit() : DB::rollBack();
		return $order;
	}

	/**
	 * 会员卡开卡
	 * @param $member_card
	 * @param $billId
	 * @param $params
	 * @return mixed
	 * @throws AllValidatorException
	 * @throws NotFoundException
	 */
	protected function memberCardPay($member_card, $billId, $params)
	{
		list($operation, $balance, $count, $real_amount, $payment) = array_values($params);
		DB::beginTransaction();
		try {
			// 检测订单是否已经被支付
			$billInfo = $this->billRepository->isNotPay($billId);
			//更改会员卡状态
			$member_card = $this->cardRepository->examineMemberCard($member_card->id, $operation, $billInfo->main_recommend);
//			if ($operation == 1) {
				//获取卡类
				$card_type_id = $member_card->type_id;
				$card_type = $this->cardTypeRepository->find($card_type_id);

				$member_id = $member_card->member_id;
				$store_id = $member_card->store_id;
				$category = $member_card->attribute;
				//会员卡金额添加
				$this->cardRepository->recharge($member_card->id, $balance, $count);
				//会员卡开卡记录添加
				$member_card_flow = $this->memberCardFlowRepository->init($member_card->id, $member_id, $store_id, $category, $billInfo->main_recommend, $count, $balance, $real_amount, $payment);
				$this->memberCardFlowAndBillAndAmountFlower($payment, $card_type, $real_amount, $billInfo->main_recommend, $store_id, $member_card_flow, $billInfo, $balance);
				//发消息
//				$this->messageCardNotice($store_id, $member_card, $billInfo->main_recommend);
//			}
			DB::commit();
			return true;
		} catch (AllValidatorException $allValidatorException) {
			DB::rollBack();
			throw new AllValidatorException(['msg' => $allValidatorException->msg]);
		}
	}

	/**
	 * 会员卡订单回写 订单流水 账单流水 总帐记录
	 * @param $payment
	 * @param $card_type
	 * @param $real_amount
	 * @param $user_id
	 * @param $store_id
	 * @param $member_card_flow
	 * @param $billInfo
	 * @param $balance
	 * @throws NotFoundException
	 */
	protected function memberCardFlowAndBillAndAmountFlower($payment, $card_type, $real_amount, $user_id, $store_id, $member_card_flow, $billInfo, $balance)
	{

		$this->memberCardOrderRepository->isExited($billInfo->order_id);
		$royalty = $assist_royalty = 0;
		// 主推荐人的提成
		if (!empty($billInfo->main_recommend)) {
			// 提成比例
			$royaltyRate = bcdiv($card_type->royalty, 100, 2);
			// 提成金额
			$royalty = bcmul($royaltyRate, $real_amount, 2);
			$this->royaltyRepository->createRoyalty($billInfo->main_recommend, $store_id, 2, $member_card_flow->id, $real_amount, 0, $royalty);
		}

		// 副推荐人的提成
		if (!empty($billInfo->assist_recommend)) {
			$assist_royalty_rate = bcdiv($card_type->assist_royalty, 100, 2);
			$assist_royalty = bcmul($assist_royalty_rate, $real_amount, 2);
			$this->royaltyRepository->createRoyalty($billInfo->assist_recommend, $store_id, 2, $member_card_flow->id, $real_amount, 0, $assist_royalty);
		}
		//加流水
		$profit = bcsub($real_amount, bcadd($royalty, $assist_royalty, 2), 2);

		$this->amountFlowRepository->add($store_id, $user_id, 2, $member_card_flow->id, $card_type->price, $real_amount, $profit, 0, $royalty, 0, 0, $payment);

		$this->memberCardOrderRepository->update(['status' => 2, 'price' => $card_type->price, 'real_price' => $real_amount], $billInfo->order_id);
		// 回写总的订单表
		$this->billRepository->updateBillByCategoryAndOrderId($billInfo->id, $balance, $real_amount,1);
	}


	/**
	 * 会员卡办理发送消息
	 * @param $store_id
	 * @param $member_card
	 * @param $user_id
	 */
	protected function messageCardNotice($store_id, $member_card, $user_id)
	{
		$store_name = $this->storeRepository->getStoreNameById($store_id)->store_name;
		$card_type_id = $member_card->type_id;
		$card_type_name = $this->cardTypeRepository->find($card_type_id)->name;
		$barber_name = $this->employeeRepository->find($user_id)->nick;
		$type = config('constant.message.sub_type.card_handle');
		if ($member_card->member_id) {
			$scene = config('constant.message.scene.wx');
			$content = '您在' . $store_name . '的会员卡办理成功，卡号为：' . $member_card->num;
			$noticeFace = config('constant.message.wx_image');
			$noticeTitle = $store_name;
			$noticeTitleRight = '';
			$contentLeft = $card_type_name;
			$contentRight = '办理：' . $barber_name;
			$datas = $this->messageRepository->makeMessageData($scene, $type, $noticeFace, $noticeTitle, $noticeTitleRight, $contentLeft, $contentRight, $content, $member_card->id);
			$this->messageRepository->addMessage($member_card->member_id, $datas, $store_id);
		}

		// 店长消息发送
		$sceneApp = config('constant.message.scene.app');
		$contentApp = "会员：" . $member_card->name . "在您的" . $store_name . '店办理会员卡成功';
		$noticeFaceApp = config('constant.message.wx_image');
		$noticeTitleApp = $member_card->name;
		$noticeTitleRightApp = $store_name;
		$contentLeftApp = $card_type_name;
		$contentRightApp = '办理人：' . $barber_name;
		$dataApp = $this->messageRepository->makeMessageData($sceneApp, $type, $noticeFaceApp, $noticeTitleApp, $noticeTitleRightApp, $contentLeftApp, $contentRightApp, $contentApp, $member_card->id);
		$this->messageRepository->sendBossMessage(config('constant.role.manager'), $store_id, $dataApp, $user_id);
	}


	/**
	 * 商品外卖
	 * @param $goods
	 * @param $billId
	 * @param $params
	 * @throws AllValidatorException
	 * @throws NotFoundException
	 */
	protected function goodsPay($goodsOrder, $billId, $params)
	{
		list($goods,$store_id, $user_id, $payment, $remark) = array_values($params);
		DB::beginTransaction();

		$totalRoyalty = $buying_sum = $real_price = $market_price= $cost = $profit= 0;

		$goodsOrderItems = $goodsOrder->items;
		foreach ($goodsOrderItems as $v){
			$newOrderItems[$v->goods_id] = $v;
		}
		foreach ($goods as $v){
			$this->salePurchaseRepository->createSalePurchase($store_id, $v['goods']->id, $v['goods']->name, 2, 2, -$v['count']);
			//减少库存
			$this->goodsStockRepository->reduceStock($v['goods_id'], $v['count']);

			if(isset($newOrderItems[$v['goods_id']])){
				$newOrderItems[$v['goods_id']]->real_price = $v['price'];
				$newOrderItems[$v['goods_id']]->count  = $v['count'];
				$newOrderItems[$v['goods_id']]->save();
				unset($newOrderItems[$v['goods_id']]);
			}else{
				$params = [
					'goods_id'   => $v['goods_id'],
					'goods_name' => $v['goods']->name,
					'price'      => $v['goods']->market_price,
					'real_price' => $v['price'],
					'count'      => $v['count'],
				];
				$this->goodsOrderItemsRepository->addItem($goodsOrder->id,$params);
			}
			//计算提成
			$royalty = ($v['goods']->royalty / 100) * $v['price'];
			$assist_royalty = ($v['goods']->assist_royalty/100)*$v['price'];
			$totalRoyalty += $royalty + $assist_royalty;
			$real_price += $v['count']*$v['price'];
			$market_price += $v['count']*$v['goods']->market_price;
			$cost  += $v['count'] * $v['goods']->buying_price;
			$profit += $v['count'] * ($v['price'] - $v['goods']->buying_price - $royalty - $assist_royalty );
//          //创建商品订单
//			$goods_order = $this->goodsOrderRepository->createGoodsOrder($store_id, $user_id, 0, 0, 0,  0, 0, $payment, $royalty, $remark);
			// 主推人提成表
			$this->royaltyRepository->createRoyalty($v['barber_id'], $store_id, 3, $goodsOrder->id, $v['price'], 0, $royalty);
			// 副推人提成
			$this->royaltyRepository->createRoyalty($v['assistant_id'], $store_id, 3, $goodsOrder->id, $v['price'], 0, $assist_royalty);
		}

		/**
		 * 删除多余的 GoodsItems
		 */
		if(!empty($newOrderItems)){
			array_map(function ($v){
				$v->delete();
				return [];
			},$newOrderItems);
		}

		$goodsOrder->buying_sum = $cost;
		$goodsOrder->market_sum = $market_price;
		$goodsOrder->royalty = $totalRoyalty;
		$goodsOrder->remark = $remark;
		$goodsOrder->real_price = $real_price;
		$goodsOrder->payment = $payment;
		$goodsOrder->save();
		//插入流水表
		$this->amountFlowRepository->add($store_id, $user_id, 3, 0, $market_price, $real_price, $profit, $cost, $royalty, 0, 0, $payment);
		$this->billRepository->updateBillByCategoryAndOrderId($billId,  $market_price, $real_price);
		DB::commit();
	}

	/**
	 * 会员卡充值
	 * @param $member_card
	 * @param $billId
	 * @param $params
	 * @return bool
	 * @throws AllValidatorException
	 * @throws NotFoundException
	 */
	protected function memberCardRecharge($member_card, $billId, $params)
	{
		list($balance, $real_amount, $count, $payment, $card_type) = array_values($params);
		$billInfo = $this->billRepository->isNotPay($billId);
		DB::beginTransaction();
		try {
			//加钱
			$this->cardRepository->recharge($member_card->id, $balance, $count);
			//创建充值记录
			$member_card_flow = $this->memberCardFlowRepository
				->recharge($member_card->id,
					$member_card->member_id,
					$member_card->store_id,
					$member_card->attribute,
					$billInfo->main_recommend,
					$count,
					$balance,
					$real_amount,
					$payment);
			$store_id = $member_card->store_id;

			$this->memberCardFlowAndBillAndAmountFlower($payment, $card_type, $real_amount, $billInfo->main_recommend, $store_id, $member_card_flow, $billInfo, $balance);
			DB::commit();
			$this->sendMessageCardRecharge($store_id, $member_card, $billInfo->main_recommend, $real_amount);
			return true;
		} catch (AllValidatorException $e) {
			DB::rollBack();
			throw new AllValidatorException(['msg' => $e->msg]);
		}

	}

	/**
	 * 充值发送消息
	 * @param $store_id
	 * @param $member_card
	 * @param $user_id
	 * @param $real_amount
	 */
	protected function sendMessageCardRecharge($store_id, $member_card, $user_id, $real_amount)
	{
		//发消息
		$store_name = $this->storeRepository->getStoreNameById($store_id)->store_name;

		$contentCate = $member_card->attribute == 1 ? ',会员卡可用次数为：' . $member_card->count . '次' : ',会员卡余额为：' . $member_card->balance . '元';
		$card_type_id = $member_card->type_id;
		$card_type_name = $this->cardTypeRepository->find($card_type_id)->name;
		$barber_name = $this->employeeRepository->find($user_id)->nick;
		$type = config('constant.message.sub_type.card_recharge');

		if ($member_card->member_id) {
			$scene = config('constant.message.scene.wx');
			$content = '您在' . $store_name . '店，给会员卡号为：' . $member_card->card_num . '成功充值' . $real_amount . $contentCate;
			$noticeFace = config('constant.message.wx_image');
			$noticeTitle = $store_name;
			$noticeTitleRight = '';
			$contentLeft = $card_type_name;
			$contentRight = null;
			$datas = $this->messageRepository->makeMessageData($scene, $type, $noticeFace, $noticeTitle, $noticeTitleRight, $contentLeft, $contentRight, $content, $member_card->id);
			$this->messageRepository->addMessage($member_card->member_id, $datas, $member_card->store_id);
		}
		$sceneApp = config('constant.message.scene.app');
		$contentApp = '会员' . $member_card->name . '在您的' . $store_name . '店成功充值' . $real_amount;
		$noticeFaceApp = config('constant.message.wx_image');
		$noticeTitleApp = $member_card->name;
		$noticeTitleRightApp = $store_name;
		$contentLeftApp = $card_type_name;
		$contentRightApp = "办理人：" . $barber_name;
		$datasApp = $this->messageRepository->makeMessageData($sceneApp, $type, $noticeFaceApp, $noticeTitleApp, $noticeTitleRightApp, $contentLeftApp, $contentRightApp, $contentApp, $member_card->id);
		$this->messageRepository->sendBossMessage(config('constant.role.manager'), $member_card->store_id, $datasApp, $user_id);
	}

	/**
	 * 会员卡消费处理
	 * @param $memberCardId
	 * @param $serviceId
	 * @param $discountRealPrice
	 * @param $count
	 * @param $payment
	 * @return array|bool
	 * @throws AllValidatorException
	 * @throws NotFoundException
	 */
	protected function memberCardConsumeHandle($memberCardId, $serviceIds, $discountRealPrice, $payment)
	{
		$result = false;
		if (($payment == config('constant.payment.member_card')) && !empty($memberCardId)) {

			$cardInfo = $this->cardRepository->isSuitableByServiceId($serviceIds, $memberCardId);

			if (floatval($discountRealPrice) > floatval($cardInfo->balance)) {
				throw  new AllValidatorException(['msg' => '对不起，您的会员卡余额不足，请充值！当前余额为:' . $cardInfo->balance . '元']);
			}

			$cardInfo->balance -= $discountRealPrice;

			$consumptionInfo = "您本次消费：" . $discountRealPrice . "元，会员卡余额：" . $cardInfo->balance . "元";

			if ($cardInfo->attribute == config('constant.memberCard.cardType.count')) {
				$cardInfo->count = floor($cardInfo->balance / $cardInfo->cardType->unit_price);
			}
			$cardInfo->save();
			$result = [
				'card_info'        => $cardInfo,
				'consumption_info' => $consumptionInfo
			];

		} elseif (($payment == config('constant.payment.member_card')) && empty($memberCardId)) {
			throw new NotFoundException(['msg' => '请选择你需要支付的会员卡！']);
		}
		return $result;
	}

	/**
	 * 二级订单和会员的县令币处理
	 * @param $billId
	 * @param $order
	 * @param $orderItems
	 * @param $payment
	 * @param $priceInfo
	 * @param bool $isOnLine
	 * @return array
	 * @throws AllValidatorException
	 * @throws NotFoundException
	 */
	protected function orderItemMemberCoinHandle($billId, $order, $orderItems, $payment, $priceInfo, $isOnLine=true,$memberCoupon=Null)
	{
		if ($isOnLine) {
			if ($order->member_id) {
				$memberCoin = $this->memberCoinRepository->consumeCoin($order->member_id, $order->store_id, 2, 1, 1, $order->id);
				$coin = $this->memberRepository->updateCoin($order->member_id, 2);
			}
		}

		foreach ($orderItems as $v) {
			// 写orderItem表
			$orderItem = $this->orderItemRepository->addOrderItemInfo($order->id, $v['service_id'], $v['service']->name, $v['service']->price, $v['price'], $v['count'], $v['barber_id'], $v['assistant_id']);
			// 写积分
			if ($isOnLine) {
				$userCoin = $this->userCoinRepository->add($v['barber_id'], $order->store_id, 0.1, 1, $order->id);
			}
		}



		// 写入订单服务表
		$costAndProfit = $this->royaltyToBarberAndAssistant($billId, $order, $payment, $orderItems, $priceInfo);

		// 计算店铺的纯利润
		$order->profit = $costAndProfit['order_profit'];

		// 使用优惠券
		if(isset($memberCoupon)){
			$coupon = $memberCoupon->coupon;
			if($coupon->use_condition  < $order->real_price){
				throw new NotFoundException(['msg'=>'优惠券使用条件不满足！']);
			}

			switch ($coupon->type){
				case 1:
					$order->real_price -= $coupon->money;
					$order->profit  -=  $coupon->money;
					break;
				case 2:
					$order->real_price = bcmul(($coupon->discount * 0.01), $order->real_price,2);
					$order->profit -= bcmul(((100 -$coupon->discount) * 0.01), $order->real_price,2);
					break;
				case 3:
					$order->real_price = 0;
					$order->profit = 0;
					break;
			}

			$memberCoupon->use_time = date('Y-m-d H:i:s');
			$memberCoupon->status = 1;
			$memberCoupon->save();
		}

		$order->save();
		$serviceList = array_column($orderItems,'service');
		// 订单完成通知
		if ($order->member_id) {
			$this->orderFinishedToMember($order, $serviceList);
		}

		$result = [
			'order' => $order,
			'flag'  => $isOnLine ? !empty($order) && !empty($orderItem) && !empty($userCoin) : !empty($order) && !empty($orderItem)
		];

		return $result;
	}

	/**
	 * 会员卡消费流水并发送消费信息
	 * @param $order
	 * @param $memberCardHandle
	 * @param $count
	 * @param $service
	 * @return bool
	 */
	protected function memberCardFlowMessage($order, $memberCardHandle, $count, $service=null)
	{
		$flag = True;
		//会员卡支付
		if (($order->payment == config('constant.payment.member_card')) && !empty($order->member_card_id)) {
			$flowInfo = $this->memberCardFlowRepository->addFlowMemberCard($memberCardHandle['card_info']->attribute, $memberCardHandle['card_info']->id, $memberCardHandle['card_info']->member_id, $order->barber_id, $memberCardHandle['card_info']->store_id, config('constant.memberCard.type.consume'), $order->id, $count, $order->real_price);
			$flag = empty($flowInfo) ? false : true;
			// 会员卡发送消息
//			$this->memberCardConsumeMessage($order, $memberCardHandle['card_info'], $service, $memberCardHandle['consumption_info'], $order->real_price);
		}
		return $flag;
	}

	/**
	 * 店铺等级处理
	 * @param $order
	 */
	protected function storeLevelHandel($order)
	{
		$storeOrder = $this->orderRepository->getFinishedOrderNums($order->store_id);
		$this->storeRepository->updateStore($order->store_id, ['order_sum' => $storeOrder]);
	}


	/**
	 * 理发师和助理提成处理
	 * @param $billId
	 * @param $order
	 * @param $payment
	 * @param $orderItems
	 * @param $priceInfo
	 * @return array
	 * @throws AllValidatorException
	 * @throws NotFoundException
	 */
	protected function royaltyToBarberAndAssistant($billId, $order, $payment, $orderItems,$priceInfo)
	{
		$orderProfit = 0;
		// 支付方式提成
		$paymentRoyalty = $this->storePaymentRoyaltyRepository->findByStoreId($order->store_id);
		$paymentList = array_flip(config('constant.payment'));
		//支付方式提成
		$paymentRoyalty = $paymentRoyalty[$paymentList[$payment]];
		foreach ($orderItems as $v) {
			// 理发师提成
			$royalty = isset($v['royalty']) ? $v['royalty']->royalty : 0;
			// 服务成本
			$costRate =isset($v['service']->cost)  ? bcmul($v['service']->cost, 0.01, 2) : 0;
			$singleCost = bcmul($v['service']->price, $costRate, 2);
			$cost = bcmul($singleCost, $v['count'], 2);

			//去掉成本的真实付款价格
			$totalSinglePrice = bcmul($v['price'],$v['count'],2);
			$orderPriceToRoyalty = bcsub($totalSinglePrice, $cost, 2);
			// 写入提成表
			$barberRoyalty = $this->royaltyRepository->addOrderRoyalty($v['barber_id'], $order->store_id, $order->id, $v['price'], $royalty, $orderPriceToRoyalty, 1, $paymentRoyalty);
			// 理发师总提成
			$barber_royalty = $barberRoyalty->amount;

			// 订单的净利润 减去理发师提成
			$orderProfit += bcsub($orderPriceToRoyalty, $barberRoyalty->amount, 2);

			// 助理提成 按服务去成本后的价格计算
			if ($v['assistant_id']) {
				// 助理提成
				$assistantRoyalty = isset($v['royalty']) ? $v['royalty']->assistant_royalty : 0;

				$asRoyalty = $this->royaltyRepository->addOrderRoyalty($v['assistant_id'], $order->store_id, $order->id, $orderPriceToRoyalty, $assistantRoyalty, $orderPriceToRoyalty, 1, $paymentRoyalty);
				// 订单的净利润 减去助理提成
				$orderProfit = bcsub($orderProfit, $asRoyalty->amount, 2);

			}
		}

		// 查询理发师提成
		$absOrderProfit = round(abs($orderProfit), 2);
		$orderProfit = $orderProfit >= 0 ? $absOrderProfit : '-1' * $absOrderProfit;

		// 会员卡优惠价格
		$specialPrice = bcsub($order->price, $priceInfo['total_price'], 2);
		// 理发师或者店长优惠价格
		$personalSpecialPrice = $priceInfo['total_price'] == $order->real_price ? 0 : bcsub($priceInfo['total_price'], $order->real_price, 2);
		// 总的资金流水表
		$this->amountFlowRepository->add($order->store_id, $order->barber_id, 1, $order->id, $order->price, $order->real_price, $orderProfit, $cost, $barber_royalty, $specialPrice, $personalSpecialPrice, $order->payment);
		// 检测订单是否已经被支付
		$this->billRepository->isNotPay($billId);
		// 回写总的订单表
		$this->billRepository->updateBillByCategoryAndOrderId($billId, $order->price, $order->real_price);
		$result = [
			'order_profit' => $orderProfit,
			'cost'         => $cost
		];
		return $result;
	}

	/**
	 * 订单完成发送消息给用户
	 * @param $order
	 * @param $service
	 */
	protected function orderFinishedToMember($order, $serviceList)
	{
		$noticeFace = isset($order->user->picture) ? $order->user->picture->image : "";
		$noticeTitle = isset($order->user) ? $order->user->nick : (isset($order->appointment) ? $order->appointment->nick : $order->appointment->mobile);

		$noticeTitleRight = isset($order->store->name) ? $order->store->name : '-'; // 理发店名称
		$contentLeft = array_reduce($serviceList,function ($str,$v){
			$str .= $v->name;
		},'');
//		$service->name;  // 服务名称
		$contentRight = $order->finish_time;

		$MessageContent = '为您服务的理发师编号为' . $order->barber_id . ",您的订单编号为：" . $order->order_no . "，期待您下次光临！";
		$MessageInfo = $this->messageRepository->makeMessageData(config('constant.message.scene.wx'), config('constant.message.sub_type.order_finish'), $noticeFace, $noticeTitle, $noticeTitleRight, $contentLeft, $contentRight, $MessageContent, $order->id);
		$message = $this->messageRepository->addMessage($order->member_id, $MessageInfo, $order->store_id);
	}
}